package com.yurun.service.impl;

import com.yurun.entity.User;
import com.yurun.exception.PersistenceException;
import com.yurun.mapper.UserMapper;
import com.yurun.service.UserService;
import com.yurun.util.HashUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService, UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void addUser(User user){
        if(userMapper.addUser(user)!=1){
            throw new PersistenceException("添加用户失败");
        }
    }

    @Override
    public void deleteUserById(Long id){
        if(userMapper.deleteUserById(id)!=1){
            throw new PersistenceException("删除用户失败");
        }
    }

    @Override
    public void updateUserAvatorById(Long id,String avator){
        if(userMapper.updateUserAvatorById(id, avator)!=1){
            throw new PersistenceException("更新用户头像失败");
        }
    }

    @Override
    public List<User> getUserList(){
        return userMapper.getUserList();
    }

    @Override
    public User findByUsernameAndPassword(String username,String password){
        User user=userMapper.findByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        if(!HashUtils.matchBC(password,user.getPassword())){
            throw new UsernameNotFoundException("密码错误");
        }
        return user;
    }

    /**
     * 重写 UserDetailService-laodUserByUsername
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException{
        User user=userMapper.findByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }
}
